package com.yangyang.androidconnect;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.nsd.NsdManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;

import com.yangyang.androidconnect.common.NetworkMonitor;
import com.yangyang.androidconnect.config.ProjectConfig;
import com.yangyang.androidconnect.mdns.NsdHelper;
import com.yangyang.androidconnect.phoneinfo.DataCollectionService;
import com.yangyang.androidconnect.phoneinfo.DatabaseHelper;
import com.yangyang.androidconnect.phoneinfo.PermissionManager;
import com.yangyang.androidconnect.phoneinfo.model.CallRecord;
import com.yangyang.androidconnect.phoneinfo.model.Contact;
import com.yangyang.androidconnect.phoneinfo.model.SMSRecord;
import com.yangyang.androidconnect.service.FileIndexService;
import com.yangyang.androidconnect.task.DCIMFileObserver;
import com.yangyang.androidconnect.util.IpUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.StringJoiner;

public class MainActivity extends AppCompatActivity implements FileIndexService.IndexingListener {

    private static final String KEY_INDEXING_STATUS = "indexing_status";
    private static final String KEY_IS_INDEXING = "is_indexing";
    private static final String KEY_TOTAL_FILES = "total_files";

    private String currentStatus = "";
    private boolean isIndexing = false;
    private int totalFiles = 0;

    private static String TEXT_DATA = "";
    private static final String TAG = "MainActivity";
    public static Context context;
    TextView textView;
    TextView indexingStatusText; // 新增一个TextView用于显示索引状态

    private NetworkMonitor networkMonitor;

    //1.读与写的权限先定义到静态字符数组中：
    private static String[] PERMISSIONS_STORAGE = {android.Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static int REQUEST_PERMISSION_CODE = 1;
    // 在 Constants.java 或 MainActivity.java 中定义
    public static final int REQUEST_CODE_NOTIFICATION = 1001;
    public static final int REQUEST_CODE_OVERLAY = 1002;
    public static final int REQUEST_CODE_FULL_SCREEN_INTENT = 1003;
    private static final int REQUEST_CODE_PERMISSIONS = 1001;
    private static final int REQUEST_CODE_MANAGE_STORAGE = 1002;

    private PermissionManager permissionManager;
    private DataCollectionService dataService;
    private DatabaseHelper databaseHelper;

    //mDNS
    private NsdHelper nsdHelper;
    private NsdManager nsdManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            context = this;

            initComponents();
            checkAndRequestPermissions();

            checkPermission();
            textView = findViewById(R.id.text_result);
            indexingStatusText = findViewById(R.id.indexing_status_text);

            // 恢复状态
            if (savedInstanceState != null) {
                currentStatus = savedInstanceState.getString(KEY_INDEXING_STATUS, "");
                isIndexing = savedInstanceState.getBoolean(KEY_IS_INDEXING, false);
                totalFiles = savedInstanceState.getInt(KEY_TOTAL_FILES, 0);
                indexingStatusText.setText(currentStatus);
            }

            init();
            startObserver();

            networkMonitor = new NetworkMonitor(this);

            // 启动文件索引
            //startFileIndexing();

            // 只在应用真正启动时执行（不是由主题切换等配置变化重建）
            if (savedInstanceState == null && isTaskRoot()) {
                startFileIndexing();
            }
        } catch (Exception e) {
            textView.setText(e.getMessage());
        }
    }


    @Override
    protected void onDestroy() {
        // 判断是否是最终销毁（应用退出）
        if (isFinishing()) {
            performExitTasks();
        }
        super.onDestroy();
    }

    private void performExitTasks() {
        // 执行退出时的操作
        Log.d("MainActivity", "Activity 被销毁，执行退出操作");
        nsdHelper.unregisterService();
    }

    private void initComponents() {
        permissionManager = new PermissionManager();
        dataService = new DataCollectionService(this);
        databaseHelper = new DatabaseHelper(this);
    }


    private void checkAndRequestPermissions() {
        if (PermissionManager.hasPermissions(this, PermissionManager.Permissions.ALL)) {
            // 所有权限都已授予，开始收集数据
            //collectAndSaveData();
        } else {
            // 请求权限
            PermissionManager.requestPermissions(
                    this,
                    PermissionManager.Permissions.ALL,
                    REQUEST_CODE_PERMISSIONS
            );
        }
        //---
        // 1. 首先检查媒体文件权限
        if (!PermissionUtils.hasMediaPermissions(this)) {
            PermissionUtils.requestMediaPermissions(this);
            return;
        }

        // 2. 如果需要访问所有文件，检查管理权限
        if (!PermissionUtils.hasManageExternalStoragePermission(this)) {
            showManageStoragePermissionDialog();
            return;
        }

        // 所有权限都已授予
        onAllPermissionsGranted();
    }

    private void showManageStoragePermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("需要文件管理权限")
                .setMessage("为了访问设备上的所有文件，需要授予文件管理权限")
                .setPositiveButton("去设置", (dialog, which) -> {
                    PermissionUtils.requestManageExternalStoragePermission(this);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void collectAndSaveData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 收集联系人
                    List<Contact> contacts = dataService.getAllContacts();
                    databaseHelper.saveContacts(contacts);

                    // 收集通话记录
                    List<CallRecord> callRecords = dataService.getCallLogs();
                    databaseHelper.saveCallLogs(callRecords);

                    // 收集短信记录
                    List<SMSRecord> smsRecords = dataService.getSMSRecords();
                    databaseHelper.saveSMSRecords(smsRecords);

                    // 在主线程显示结果
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showSuccessMessage();
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showErrorMessage(e.getMessage());
                        }
                    });
                }
            }
        }).start();
    }

    private void showPermissionDeniedDialog(List<String> deniedPermissions) {
        StringBuilder message = new StringBuilder("以下权限被拒绝，功能将受限：\n");
        for (String permission : deniedPermissions) {
            message.append(getPermissionName(permission)).append("\n");
        }

        new AlertDialog.Builder(this)
                .setTitle("权限提示")
                .setMessage(message.toString())
                .setPositiveButton("确定", null)
                .show();
    }

    private String getPermissionName(String permission) {
        switch (permission) {
            case Manifest.permission.READ_CONTACTS:
                return "读取联系人";
            case Manifest.permission.READ_CALL_LOG:
                return "读取通话记录";
            case Manifest.permission.READ_SMS:
                return "读取短信";
            default:
                return permission;
        }
    }

    private void showSuccessMessage() {
        Toast.makeText(this, "数据收集完成", Toast.LENGTH_SHORT).show();
    }

    private void showErrorMessage(String message) {
        Toast.makeText(this, "数据收集失败: " + message, Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(KEY_INDEXING_STATUS, indexingStatusText.getText().toString());
        outState.putBoolean(KEY_IS_INDEXING, isIndexing);
        outState.putInt(KEY_TOTAL_FILES, totalFiles);
    }


    @Override
    protected void onStart() {
        super.onStart();
        // 注册网络监听
        networkMonitor.startMonitoring();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 取消监听
        networkMonitor.stopMonitoring();
        EventBus.getDefault().unregister(this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        // ✅ 每次界面显示时都更新IP地址
        updateIpAddress();
    }

    // 处理网络变化事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNetworkChange(NetworkMonitor.NetworkChangeEvent event) {
        updateIpAddress();
    }


    // 添加方法：
    private void startFileIndexing() {
        FileIndexService indexService = MyApplication.getInstance().getFileIndexService();
        //FileIndexService indexService = new FileIndexService(this);
        indexService.setIndexingListener(this); // 设置监听器
        String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        indexService.startIndexing(rootPath);
    }


    // 更新IP地址的方法
    private void updateIpAddress() {
        new Thread(() -> {
            runOnUiThread(() -> {
                StringJoiner joiner = new StringJoiner("\n", "", "");
                joiner.add("http://" + IpUtil.getLocalIPv4IP() + ":" + ProjectConfig.SERVER_PORT);
                //joiner.add("http://" + IpUtilV6.getLocalIPv6Address() + ":" + ProjectConfig.SERVER_PORT);
                textView.setText(joiner.toString());
            });

        }).start();

        startServiceDiscovery();
    }

    //开始注册mDNS服务
    private void registerMDNSService() {
        if (nsdManager == null) nsdManager = (NsdManager) getSystemService(Context.NSD_SERVICE);
        if (nsdHelper == null) nsdHelper = new NsdHelper(nsdManager);
        // 启动服务（假设服务运行在 8080 端口）
        nsdHelper.registerService(ProjectConfig.SERVER_PORT);
    }

    public void startServiceDiscovery() {
        if (hasMulticastPermission()) {
            registerMDNSService();
        } else {
            requestMulticastPermission();
        }
    }


    private boolean hasMulticastPermission() {
        return ContextCompat.checkSelfPermission(this,
                Manifest.permission.CHANGE_WIFI_MULTICAST_STATE) == PackageManager.PERMISSION_GRANTED;
    }

    private static final int REQUEST_MULTICAST_PERMISSION = 1001;

    private void requestMulticastPermission() {
        if (!hasMulticastPermission()) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CHANGE_WIFI_MULTICAST_STATE},
                    REQUEST_MULTICAST_PERMISSION);
        }
    }


    private void init() throws Exception {
        //启动后台服务
        Intent serviceIntent = new Intent(this, MyForegroundService.class);
        startService(serviceIntent);
        textView.setText("");
        try {
            updateIpAddress();

            if (1 == 2) {
                //打开通知权限
                if (!checkNotificationPermission()) {
                    requestNotificationPermission();
                }
                //悬浮窗权限
                if (!checkOverlayPermission()) {
                    requestOverlayPermission();
                }
                //后台弹窗权限
                if (!checkFullScreenIntentPermission()) {
                    requestFullScreenIntentPermission();
                }
            }
        } catch (Exception e) {
            textView.setText("IPv4\nIPv6");
        }
    }

    /**
     * 启动监听
     */
    public void startObserver() {
        DCIMFileObserver observer = new DCIMFileObserver(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath());
        observer.startWatching();
    }

    /**
     * 检查文件读写权限
     */
    public void checkPermission() {
        //如果没有开启权限 那么就去开启
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.VERSION.SDK_INT < 30) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
            }
        }

        //申请权限：
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 适配android11读写权限
            if (Environment.isExternalStorageManager()) {
                //已获取android读写权限
            } else {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_PERMISSION_CODE);
            }
        }
    }

    /**
     * 适配文件权限
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        // 适配android 11 一下版本 读写权限
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                Log.i("MainActivity", "申请的权限为：" + permissions[i] + ",申请结果：" + grantResults[i]);
            }
        }

        if (requestCode == REQUEST_CODE_NOTIFICATION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 通知权限已授予
            }
        } else if (requestCode == REQUEST_CODE_FULL_SCREEN_INTENT) {
            // 处理后台弹窗权限结果
        }

        if (requestCode == REQUEST_CODE_PERMISSIONS) {
            PermissionManager.handlePermissionResult(
                    requestCode,
                    permissions,
                    grantResults,
                    new PermissionManager.PermissionCallback() {
                        @Override
                        public void onPermissionResult(int requestCode, boolean allGranted,
                                                       List<String> grantedPermissions,
                                                       List<String> deniedPermissions) {
                            if (allGranted) {
                                collectAndSaveData();
                            } else {
                                // 处理权限被拒绝的情况
                                showPermissionDeniedDialog(deniedPermissions);
                            }
                        }
                    }
            );
        }

        if (requestCode == REQUEST_MULTICAST_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予，开始注册mDNS服务
                registerMDNSService();
            } else {
                // 权限被拒绝，提示用户
                Toast.makeText(this, "需要多播权限才能发现本地服务", Toast.LENGTH_SHORT).show();
            }
        }

    }

    //显示悬浮窗
    public void showFlowWindow() {
//        if (checkOverlayPermission()) {
//            // 创建悬浮窗
//            WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
//            View overlayView = LayoutInflater.from(this).inflate(R.layout.floating_view, null);
//            WindowManager.LayoutParams params = new WindowManager.LayoutParams(
//                    WindowManager.LayoutParams.WRAP_CONTENT,
//                    WindowManager.LayoutParams.WRAP_CONTENT,
//                    Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ?
//                            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY :
//                            WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
//                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
//                    PixelFormat.TRANSLUCENT
//            );
//            windowManager.addView(overlayView, params);
//        } else {
//            requestOverlayPermission();
//        }
    }

    //发送通知（带后台弹窗）
    public void sendTongZhi() {
        if (checkNotificationPermission()) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel(
                    "channel_id", "Channel Name", NotificationManager.IMPORTANCE_HIGH
            );
            notificationManager.createNotificationChannel(channel);

            Intent intent = new Intent(this, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);

            Notification notification = new NotificationCompat.Builder(this, "channel_id")
                    .setContentTitle("Title")
                    .setContentText("Message")
                    .setSmallIcon(R.drawable.ic_notification)
                    .setFullScreenIntent(pendingIntent, true) // 使用后台弹窗权限
                    .build();

            notificationManager.notify(1, notification);
        }
    }


    // 检查通知权限是否已授予
    private boolean checkNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            return ContextCompat.checkSelfPermission(this,
                    Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED;
        }
        return true; // Android 13 以下默认有权限
    }

    // 请求通知权限
    private void requestNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{Manifest.permission.POST_NOTIFICATIONS},
                    REQUEST_CODE_NOTIFICATION
            );
        }
    }


    // 检查悬浮窗权限是否已授予
    private boolean checkOverlayPermission() {
        return Settings.canDrawOverlays(this);
    }

    // 跳转到设置页面请求悬浮窗权限
    private void requestOverlayPermission() {
        Intent intent = new Intent(
                Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:" + getPackageName())
        );
        startActivityForResult(intent, REQUEST_CODE_OVERLAY);
    }

    // 检查后台弹窗权限
    private boolean checkFullScreenIntentPermission() {
        return ContextCompat.checkSelfPermission(this,
                Manifest.permission.USE_FULL_SCREEN_INTENT) == PackageManager.PERMISSION_GRANTED;
    }

    // 请求后台弹窗权限
    private void requestFullScreenIntentPermission() {
        ActivityCompat.requestPermissions(
                this,
                new String[]{Manifest.permission.USE_FULL_SCREEN_INTENT},
                REQUEST_CODE_FULL_SCREEN_INTENT
        );
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_OVERLAY) {
            if (Settings.canDrawOverlays(this)) {
                // 悬浮窗权限已授予
            }
        }

        if (requestCode == REQUEST_CODE_MANAGE_STORAGE) {
            if (PermissionUtils.hasManageExternalStoragePermission(this)) {
                onAllPermissionsGranted();
            } else {
                showPermissionDeniedDialog();
            }
        }
    }

    private void onAllPermissionsGranted() {
        // 所有权限都已授予，执行文件操作
        //Toast.makeText(this, "所有权限已授予", Toast.LENGTH_SHORT).show();
        // 开始你的文件操作...
    }

    private void showPermissionDeniedDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("权限被拒绝")
                .setMessage("没有必要的权限，部分功能可能无法正常使用")
                .setPositiveButton("确定", null)
                .show();
    }

    @Override
    public void onIndexingStarted() {
        runOnUiThread(() -> {
            indexingStatusText.setText("📁 文件索引中...");
        });
    }

    @Override
    public void onIndexingCompleted(boolean success, int totalFiles) {
        runOnUiThread(() -> {
            if (success) {
                indexingStatusText.setText("✅ 文件索引完成！共 " + totalFiles + " 个文件");
            } else {
                indexingStatusText.setText("❌ 文件索引失败");
            }
        });
    }

    @Override
    public void onIndexingError(String errorMessage) {
        runOnUiThread(() -> {
            indexingStatusText.setText("❌ 错误: " + errorMessage);
        });
    }
}